var express = require('express');
var router = express.Router();
const user = require("../sql/User");
const team = require("../sql/Team")
const job = require("../sql/Job");
const md5 = require('md5');
const uuid = require("uuid");

router.get('/', function(req, res, next) {
  const { employeesName } = req.session.userData;

  Promise.all([ user.find(), team.find(), job.find() ]).then(data=>{
    res.render('user', {
      employeesName,
      userData: data[0],
      teamData: data[1],
      jobData: data[2],
      index: 3
    });
  })
});

// 修改部门 和 职位
router.post('/set', async function(req, res, next) {
  let {uId, tId, jId} = req.body;

  const updateData = {};

  if(tId !== undefined){
    tId = tId ? JSON.parse(tId) : [];
    if(tId.length > 0){
      try {
        const teamData = await team.find({$or: tId.map(v=>({tId: v}))});
        updateData.team = teamData.map(v=>({tName:v.tName, tId:v.tId}));
      } catch (error) {
        res.send( {code:0, msg:'error', data:error} )
      }
    }else{
      updateData.team = [];
    }
  }  

  if(jId!==undefined){
    try {
      const jobData = await job.find({jId} , {__v:0, _id:0});
      updateData.job = jobData[0];
    } catch (error) {
      res.send( {code:0, msg:'error', data:error} )
    }
  }

  user.updateMany({uId}, updateData).then(()=>{
    res.send( {code:1, msg:'success'} );
  }).catch(code=>{
    res.send( {code:0, msg:'error', data:code} )
  })
});

// 删除用户
router.get('/deleteUser', function(req, res, next) {
  const {uId} = req.query;
  user.deleteOne({uId}).then(()=>{
    res.redirect('/user');
  }).catch(code=>{
    res.redirect('/user');
    console.error(code);
  })
});

// 重置密码
router.get('/password', function(req, res, next) {
  const { uId } = req.query;
  user.updateOne({uId},{ password:md5('123456') }).then(()=>{
    res.redirect('/user');
  }).catch(code=>{
    res.redirect('/user');
    console.error(code);
  })
});

// 添加用户
router.post('/add', async function(req, res, next) {
  const data = req.body;
  const newData = {
    uId: 'user-'+uuid.v1(),
    employeesName: data.employeesName.replace(/\s+/g, ''),
    password: md5('123456'),
    regTime: Date.now(),
    // 用户默认权限
    power: ['/order', '/order/search', '/order/add', '/order/setUser', '/order/exportTemp', '/order/export', '/', '/dashboard', '/dashboard/getData', '/setpassword', '/setpassword/set', '/customer', '/customer/add', '/customer/set', '/customer/delete']
  };
  
  if(data.team!==undefined){
    try {
      const teamData = await team.find({tId: data.team});
      newData.team = teamData.map(v=>({tName:v.tName, tId:v.tId}));
    } catch (error) {
      res.send( {code:0, msg:'error', data:error} )
    }
  }

  if(data.job!==undefined){
    try {
      const jobData = await job.find({jId: data.job});
      newData.job = jobData[0];
    } catch (error) {
      res.send( {code:0, msg:'error', data:error} )
    }
  }

  user.insertMany( newData ).then(()=>{
    res.redirect('/user');
  }).catch(code=>{
    res.redirect('/user');
    console.error(code);
  })
});

// 权限页面
router.get('/power', function(req, res, next) {
  const { employeesName } = req.session.userData;
  const { uId } = req.query;
  user.find({ uId }).then(userData=>{
    res.render('power', {
      employeesName,
      userData: userData[0],
      index: 3
    })
  })
});

// 权限修改
router.post('/power/set', function(req, res, next) {

  const {uId, powerList} = req.body;

  // 未在权限管理中展示的权限
  powerList.push('/', '/dashboard', '/dashboard/getData', '/setpassword', '/setpassword/set');

  user.updateOne({uId}, {
    power: powerList
  }).then(()=>{
    user.find({uId}).then(uData=>{
      req.session.userData.power = uData[0].power;
    })
    req.flash('success', '设置成功');
    res.redirect('/user/power?uId='+uId);
  }).catch(()=>{
    req.flash('error', '设置失败，请重试');
    res.redirect('/user/power?uId='+uId);
  })

});

module.exports = router;
